<template>
  <div class="checkout-view">
    <div class="checkout-container" style="margin-top: 650px">
      <!-- 页面头部 -->
      <div class="checkout-header">
        <a-button type="link" @click="$router.go(-1)" class="back-btn">
          <ArrowLeftOutlined />
          返回商品详情
        </a-button>
        <h1>订单结算</h1>
      </div>

      <div class="checkout-content">
        <!-- 订单信息 -->
        <div class="order-section">
          <div class="section-title">
            <h3>📋 订单信息</h3>
          </div>
          <div class="order-items">
            <div
              class="order-item"
            >
              <img :src="products?.coverImg" :alt="products?.title" class="item-image" />
              <div class="item-info">
                <h4>{{ products?.title }}</h4>
                <p class="item-spec">{{ products?.specify }}</p>
                <div class="item-meta">
                  <span class="item-shop">{{ products?.storeName}}</span>
                  <span class="item-quantity">x1</span>
                </div>
              </div>
              <div class="item-price">
                <span class="price">¥{{ products?.discountedPrice }}</span>
                <span class="total">¥{{ products?.discountedPrice}}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 收货地址 -->
        <div class="address-section">
          <div class="section-title">
            <h3>📍 收货地址</h3>
            <a-button type="link" @click="showAddressModal = true">
              <PlusOutlined />
              添加新地址
            </a-button>
          </div>
          <div class="address-list">
            <div
              v-for="address in addresses"
              :key="address.id"
              class="address-item"
              :class="{ active: selectedAddress === address.id }"
              @click="selectedAddress = address.id"
            >
              <div class="address-info">
                <div class="address-header">
                  <span class="name">{{ address.name }}</span>
                  <span class="phone">{{ address.phone }}</span>
                  <a-tag v-if="address.isDefault" color="red">默认</a-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }}
                  {{ address.district }} {{ address.detail }}
                </div>
              </div>
              <div class="address-actions">
                <a-button
                  type="link"
                  size="small"
                  @click.stop="editAddress(address)"
                >
                  <EditOutlined />
                  编辑
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  danger
                  @click.stop="deleteAddress(address.id)"
                >
                  <DeleteOutlined />
                  删除
                </a-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="payment-section">
          <div class="section-title">
            <h3>💳 支付方式</h3>
          </div>
          <div class="payment-methods">
            <div
              v-for="method in paymentMethods"
              :key="method.id"
              class="payment-method"
              :class="{ active: selectedPaymentMethod === method.id }"
              @click="selectedPaymentMethod = method.id"
            >
              <div class="method-icon">
                <component :is="method.icon" />
              </div>
              <div class="method-info">
                <h4>{{ method.name }}</h4>
                <p>{{ method.description }}</p>
              </div>
              <div class="method-radio">
                <a-radio :checked="selectedPaymentMethod === method.id" />
              </div>
            </div>
          </div>
        </div>

        <!-- 订单摘要 -->
        <div class="summary-section">
          <div class="section-title">
            <h3>💰 订单摘要</h3>
          </div>
          <div class="summary-content">
            <div class="summary-item">
              <span>商品总价：</span>

              <span>¥{{products?.discountedPrice.toFixed(2)}}</span>
            </div>
            <div class="summary-item">
              <span>运费：</span>
              <span>¥{{ 3 }}</span>
            </div>
            <div class="summary-item discount">
              <span>优惠：</span>
              <span>-¥{{ (products?.price-products?.discountedPrice).toFixed(2)}}</span>
            </div>
            <div class="summary-total">
              <span>实付金额：</span>
              <span class="total-amount">¥{{ (products?.discountedPrice+3).toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <!-- 支付按钮 -->
        <div class="payment-actions">
          <a-button
            type="primary"
            size="large"
            class="pay-btn"
            :loading="paying"
            :disabled="!selectedAddress"
            @click="handlePayment"
          >
            <CreditCardOutlined />
            {{ paying ? "支付中..." : `立即支付 ¥${ (products?.discountedPrice+3).toFixed(2)}` }}
          </a-button>
        </div>
      </div>
    </div>

    <!-- 支付成功弹窗 -->
    <a-modal
      v-model:open="showPaymentSuccess"
      title="🎉 支付成功"
      :footer="null"
      :closable="false"
      :mask-closable="false"
      width="400px"
      class="payment-success-modal"
    >
      <div class="success-content">
        <div class="success-icon">
          <CheckCircleOutlined />
        </div>
        <h3>支付成功！</h3>
        <p>您的订单已支付成功，我们会尽快为您发货</p>
        <div class="success-actions">
          <a-button type="primary" @click="goToOrders">查看订单</a-button>
          <a-button @click="goToHome">继续购物</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import {useRoute, useRouter} from "vue-router";
import {
  ArrowLeftOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CreditCardOutlined,
  CheckCircleOutlined,
  WechatOutlined,
  AlipayCircleOutlined,
  BankOutlined,
} from "@ant-design/icons-vue";
import {getProductsVo} from "@/api/productController.ts";
import {message} from "ant-design-vue";
import {editOrderStatus} from "@/api/ordersController.ts";

const router = useRouter();
const paying = ref(false);
const showPaymentSuccess = ref(false);
const showAddressModal = ref(false);
const selectedAddress = ref("");
const selectedPaymentMethod = ref("alipay");
const route = useRoute();
// 订单数据
const orderData = ref({
  products: [],
  totalAmount: 0,
  shipping: 0,
  discount: 0,
});
const products = ref<API.ProductsVO>();
const fetchProducts = async () => {
  try {
    const res = await getProductsVo({
      id: route.params.id
    });


    if (res.data.code === 0 && res.data.data) {
      products.value = res.data.data;
      orderData.value.products.push(products);
    } else {
      message.error('获取商品详情失败: ' + res.data.msg);
      await router.push('/');
    }
  } catch (error) {
    message.error('加载商品详情出错');
    console.error(error);
  }
};
onMounted(() => {
  fetchProducts();
});
// 收货地址
const addresses = ref([
  {
    id: "1",
    name: "张三",
    phone: "138****8888",
    province: "北京市",
    city: "北京市",
    district: "朝阳区",
    detail: "三里屯街道1号",
    isDefault: true,
  },
  {
    id: "2",
    name: "李四",
    phone: "139****9999",
    province: "上海市",
    city: "上海市",
    district: "浦东新区",
    detail: "陆家嘴街道2号",
    isDefault: false,
  },
]);

// 支付方式
const paymentMethods = [
  {
    id: "alipay",
    name: "支付宝",
    description: "推荐使用支付宝支付",
    icon: AlipayCircleOutlined,
  },
  {
    id: "wechat",
    name: "微信支付",
    description: "使用微信扫码支付",
    icon: WechatOutlined,
  },
  {
    id: "bank",
    name: "银行卡",
    description: "支持各大银行储蓄卡、信用卡",
    icon: BankOutlined,
  },
];

// 计算最终金额
const finalAmount = computed(() => {
  return (
    orderData.value.totalAmount +
    orderData.value.shipping -
    orderData.value.discount
  );
});

onMounted(() => {
  // 从 localStorage 获取订单数据
  const pendingOrder = localStorage.getItem("pendingOrder");
  if (pendingOrder) {
    orderData.value = JSON.parse(pendingOrder);
  }

  // 设置默认地址
  const defaultAddress = addresses.value.find((addr) => addr.isDefault);
  if (defaultAddress) {
    selectedAddress.value = defaultAddress.id;
  }
});

const editAddress = (address: any) => {
  console.log("编辑地址:", address);
};

const deleteAddress = (addressId: string) => {
  addresses.value = addresses.value.filter((addr) => addr.id !== addressId);
};

const handlePayment = async () => {
  if (!selectedAddress.value) {
    alert("请选择收货地址");
    return;
  }

  paying.value = true;

  // 模拟支付过程
  setTimeout(() => {
    paying.value = false;
    showPaymentSuccess.value = true;

    const param = ref<API.OrderEditDTO>({
      productId: route.params.id,  // 确保类型一致
      status: 2
    });
    const res =  editOrderStatus(param)
    if(res.data.data && res.data.code ){
      message.success("支付成功")
    }
  }, 2000);
};

const goToOrders = () => {
  showPaymentSuccess.value = false;
  router.push("/orders");
};

const goToHome = () => {
  showPaymentSuccess.value = false;
  router.push("/");
};
</script>

<style scoped>
.checkout-view {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 64px);
  width: 100%;
  padding: 24px 0;
}

.checkout-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 24px;
}

.checkout-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.checkout-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.checkout-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.order-section,
.address-section,
.payment-section,
.summary-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

/* 订单商品样式 */
.order-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: #fafafa;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.item-spec {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #999;
}

.item-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
}

.item-shop {
  color: #666;
}

.item-quantity {
  color: #ff4757;
  font-weight: 500;
}

.item-price {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  min-width: 80px;
}

.price {
  font-size: 14px;
  color: #666;
}

.total {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 地址样式 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.address-item:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.address-item.active {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.1);
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.name {
  font-weight: 500;
  color: #333;
}

.phone {
  color: #666;
  font-size: 14px;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  gap: 8px;
}

/* 支付方式样式 */
.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-method {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-method:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.payment-method.active {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.1);
}

.method-icon {
  font-size: 24px;
  color: #667eea;
  width: 40px;
  text-align: center;
}

.method-info {
  flex: 1;
}

.method-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.method-info p {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.method-radio {
  width: 20px;
}

/* 订单摘要样式 */
.summary-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.summary-item.discount {
  color: #ff4757;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.total-amount {
  font-size: 20px;
  font-weight: 700;
  color: #ff4757;
}

/* 支付按钮样式 */
.payment-actions {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.pay-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-width: 200px;
  margin: 0 auto;
}

/* 支付成功弹窗样式 */
.payment-success-modal :deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

.success-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 64px;
  color: #52c41a;
  margin-bottom: 16px;
}

.success-content h3 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.success-content p {
  margin: 0 0 24px 0;
  color: #666;
  font-size: 14px;
}

.success-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkout-container {
    padding: 0 16px;
  }

  .checkout-header {
    padding: 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .checkout-header h1 {
    font-size: 20px;
  }

  .order-section,
  .address-section,
  .payment-section,
  .summary-section,
  .payment-actions {
    padding: 16px;
  }

  .order-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .item-price {
    align-self: flex-end;
  }

  .address-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .address-actions {
    align-self: flex-end;
  }

  .payment-method {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .method-radio {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .checkout-container {
    padding: 0 12px;
  }

  .checkout-header {
    padding: 12px;
  }

  .checkout-header h1 {
    font-size: 18px;
  }

  .order-section,
  .address-section,
  .payment-section,
  .summary-section,
  .payment-actions {
    padding: 12px;
  }

  .pay-btn {
    width: 100%;
    min-width: auto;
  }
}
</style>
